package com.example.caorl.job1.conc0302.atomic.longaddr;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class LongDemo {


    /**
     * LongAdder采用多路归并的思想，将每个线程初始化一个cell,cell里面有一个为0的long，最终将cell总和+base值为最终结果
     * 核心思想：以空间换时间、分片计算、减少争夺共享资源的并发量、懒加载cell
     */
    public static final AtomicLong atomicLong = new AtomicLong();
    public static final LongAdder longAdder = new LongAdder();
    public static Long x = 0L;

    
    public static void main(String[] args) {
    

//        final AtomicInteger x = new AtomicInteger();
        long x = 0L;
        
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000; j++) {
                        atomicLong.getAndIncrement();
                        longAdder.increment();
                        LongDemo.x = LongDemo.x+1;
                    }
                }
            }).start();
        }
        
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("atomicLong=" + atomicLong.get());
        System.out.println("longAdder =" + longAdder.sum());
        System.out.println("x =" + x);

    }
}
